const exp = require("express");
const ejs = require("ejs");
const songModel = require("./database/model/songsBank");



const app = exp();
app.set("views",__dirname+"/html");
app.engine("html",ejs.renderFile);


app.use(exp.urlencoded({extended:false}));


app.get("/",(req,res)=>{
    songModel.find((err,data)=>{
        if(err){
            console.log(err);
        }else{
            res.render("index.html",{data});
        }
    });
})
app.get("/addSong",(req,res)=>{
    res.render("form.html");
})
app.post("/addSong",(req,res,next)=>{
    let {name,singer,price} = req.body;
    songModel.create({name,singer,price},(err,data)=>{
        if(err) return;
        res.render("jump.html",{title:"添加成功"});
        // res.redirect("/");
    });
})
app.get("/del/:_id",(req,res)=>{
    let {_id} = req.params;
    songModel.deleteOne({_id},(err,data)=>{
        if(err)return;
        res.redirect("/");
    });
})
app.get("/update",(req,res)=>{
    let {_id} = req.query;
    songModel.findById(_id,(err,data)=>{
        if(err)return;
        res.render("update.html",{data});
    });
})
app.post("/update",(req,res,next)=>{
    let {_id,name,singer,price} = req.body;
    songModel.updateOne({_id},{name,singer,price},(err,data)=>{
        if(err){
            res.send(err);
        }else{
            res.render("jump.html",{title:"修改成功"});
            // res.redirect("/");
        }
    });
})






app.listen(8080,()=>{
    console.log("启动成功!");
})